package com.sscl.baselibrary.dialog

import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatDialog
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.sscl.baselibrary.R
import com.sscl.baselibrary.exts.getParameterizedType
import com.sscl.baselibrary.exts.saveAs
import com.sscl.baselibrary.exts.saveAsUnChecked

abstract class BaseDataBindingAppCompatDialog<DB : ViewDataBinding>
 :
    AppCompatDialog, LifecycleOwner {

    /**
     * 数据绑定的对象
     */
    @Suppress("MemberVisibilityCanBePrivate")
    protected val binding: DB


    private val lifecycleRegistry = LifecycleRegistry(this)


    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 构造方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    constructor(context: Context) : this(context, R.style.FullScreenDialog)
    constructor(context: Context, theme: Int) : super(context, theme)
    constructor(
        context: Context,
        cancelable: Boolean,
        cancelListener: DialogInterface.OnCancelListener?
    ) : super(context, cancelable, cancelListener)


    init {
        val type = getParameterizedType()
        val vbClass: Class<DB> = type.actualTypeArguments[0].saveAs()
        val method = vbClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        binding = method.invoke(this, layoutInflater)!!.saveAsUnChecked()
    }

    /* * * * * * * * * * * * * * * * * * * 重写参数 * * * * * * * * * * * * * * * * * * */

    override val lifecycle: Lifecycle
        get() = lifecycleRegistry

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 重写方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.lifecycleOwner = this
        setBinding()
        doBeforeInitOthers()
        initViewData(savedInstanceState)
        initOtherData()
        initEvents()
        doAfterAll()
    }

    override fun dismiss() {
        binding.unbind()
        super.dismiss()
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 抽象方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    abstract fun setBinding()
    abstract fun doBeforeInitOthers()
    abstract fun initViewData(savedInstanceState: Bundle?)
    abstract fun initOtherData()
    abstract fun initEvents()
    abstract fun doAfterAll()
}